package com.ppm.server.base.service.impl;

import com.ppm.server.base.service.PhoneCheckService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author Administrator
 */
@Service
@Transactional(rollbackFor = Exception.class, isolation = Isolation.REPEATABLE_READ)
@Slf4j
public class PhoneCheckServiceImpl implements PhoneCheckService {

    private static final String PHONE_CHECK_KEY = "phone:check:";

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public boolean sendVerificationCode(String phone) {
        //TODO 发送验证码给用户手机
        String value = "123456";

        String key = PHONE_CHECK_KEY + phone;
        redisTemplate.opsForValue().set(key, value, 60, TimeUnit.SECONDS);

        return true;
    }

    @Override
    public String getVerificationCode(String phone) {
        String key = PHONE_CHECK_KEY + phone;
        if (redisTemplate.opsForValue().get(key) == null) {
            return null;
        }
        return redisTemplate.opsForValue().get(key).toString();
    }

    public static String getFourRandom() {
        Random random = new Random();
        String fourRandom = random.nextInt(10000) + "";
        int randLength = fourRandom.length();
        if (randLength < 4) {
            for (int i = 1; i <= 4 - randLength; i++) {
                fourRandom = "0" + fourRandom;
            }
        }
        return fourRandom;
    }

}
